/**
 * Created by hdt3213 on 16-8-23.
 */

var VACANT = 0, BLACK = 1, WHITE = -1, DROWN = -2, ILLEGAL = -3;
var LEN = 15;
var status = 0; // 0:stop, 1:local, 2:auto, 3:online

function revert_role(role) {
    return  -role;
}

function Model() {
    this.board = [];  //[[role, ...]]
    this.history = [];  //[(x, y, role), ...]
    this.gameStarted = false;
    
    this.clear();
}

Model.prototype.clear = function () {
    // gameStarted
    this.gameStarted = false;
    // board
    this.board = [];
    for (var i = 0; i < LEN; i++) {
        var line = [];
        for (var j = 0; j < LEN; j++) {
            line.push(VACANT);
        }
        this.board.push(line);
    }
    // history
    this.history = [];
};

Model.prototype.startGame = function () {
    this.clear();
    this.gameStarted = true;
};

Model.prototype.getRole = function() {
    var role = BLACK;
    if (this.history.length % 2 == 1) {
        role = WHITE;
    }
    return role;
};

Model.prototype.getPos = function(x, y) {
    if (x < LEN && y < LEN && x >= 0 && y >= 0) {
        return this.board[x][y];
    }
    else  {
        return ILLEGAL;
    }
};

Model.prototype.newStep = function(x, y) {
    x = Number(x);
    y = Number(y);
    if (!this.gameStarted) {
        return null;
    }
    // get role
    var role = this.getRole();
    // vacant validate
    if (this.board[x][y] != VACANT) {
        return null;
    }
    // add step history
    this.history.push([x, y, role]);
    // update board
    this.board[x][y] = role;
    return role;
};

Model.prototype.retract = function () {
    if (!this.gameStarted || this.history.length == 0) {
        return false;
    }
    // get last step
    var step = this.getLastStep();
    var x = step[0], y = step[1];
    // rollback board
    this.board[x][y] = VACANT;
    // rollback step history
    this.history.pop();
    return step;
};

Model.prototype.getLastStep = function () {
    if (this.history.length == 0) {
        return null;
    }
    return  this.history.slice(-1)[0];  // (x, y, role)
};

var model = new Model();

